package kk.learn.scala.work._4

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}

class AActor extends Actor {
  // 查找BActor
  val rival: ActorSelection = this.context.actorSelection("/user/BActor")

  //接收消息并进行处理
  override def receive: Receive = {
    case "start" =>
      println("start, ok!")
      println("我打")
      rival ! "我打"
    case x: Int if (x >= 1 && x <= 18) =>
      println(s"厉害！佛山无影脚 第 $x 脚")
      rival ! x
  }

}

class BActor extends Actor {
  // 查找AActor
  val rival: ActorSelection = this.context.actorSelection("/user/AActor")

  //接收消息并进行处理
  override def receive: Receive = {
    case "我打" =>
      println(s"挺猛， 看我降龙十八掌...第 1 掌")
      rival ! 1

    case x: Int if (x >= 1 && x < 18) =>
      println(s"挺猛， 看我降龙十八掌...第 ${x + 1} 掌")
      rival ! (x + 1)

    case x: Int if (x >= 18) =>
      println("告辞")

  }

}

object HelloActor {

  //通过ActorSystem创建线程池对象myFactory
  private val myFactory = ActorSystem("myFactory")
  //创建两个Actor
  private val aActorRef: ActorRef = myFactory.actorOf(Props[AActor], "AActor")
  private val bActorRef: ActorRef = myFactory.actorOf(Props[BActor], "BActor")

  def main(args: Array[String]): Unit = {
    println("AActor 出招了...")
    aActorRef ! "start"

    //让程序休眠100毫秒
    println("程序没有到这里")
    Thread.sleep(1000)

  }
}
